package com.haredot.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.haredot.entity.Course;
import com.haredot.entity.Student;
import com.haredot.entity.User;
import com.haredot.mapper.StudentMapper;
import com.haredot.service.StudentService;
import com.haredot.vo.LayuiPage;
import com.haredot.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public R<Student> save(Student student) {

        // 查询学号是否已存在
        Student stu = studentMapper.selectByPrimaryKey(student.getId());

        if (stu != null) return R.<Student>fail().data(Map.of("id", "学号已存在"));

        studentMapper.insert(student);

        return R.<Student>ok().data(student);
    }

    @Override
    public R<Page<Student>> queryStudentList(LayuiPage layuiPage, Long sno, User user) {


        if ("student".equals(user.getRole())) {
            sno = user.getUsername();
        }
        final Long studentId = sno ;
        // 分页查询所有的学生信息
        Page<Student> page = PageHelper.startPage(layuiPage)
                .doSelectPage(() -> studentMapper.findAll(studentId));

        return R.<Page<Student>>ok().data(page);

    }

    @Override
    public R<Student> queryStudentById(Long sno) {
        Student student = studentMapper.selectByPrimaryKey(sno);
        return R.<Student>ok().data(student);
    }

    @Override
    public R<Student> modify(Student student) {
        studentMapper.updateByPrimaryKey(student);

        return R.<Student>ok().data(student);
    }

    @Override
    public R<?> remove(Long sno) {
        studentMapper.remove(sno);
        return R.ok().build();
    }

    @Override
    public R<?> batchRemove(List<Long> ids) {
        studentMapper.batchRemove(ids);
        return R.ok().build();
    }

    @Override
    public R<Course> queryCourseListBySno(Long sno) {
        List<Course> list = studentMapper.findCourseListBySno(sno);
        return R.<Course>ok().data(list);
    }

    @Override
    public R<?> bindCourse(Long sno, List<Integer> courseIds) {
        // 删除 sno 选中的所有课程
        studentMapper.removeCourseBySno(sno);

        if (!courseIds.isEmpty()) {
            studentMapper.saveCourseAndSno(sno, courseIds);
        }

        return R.ok().build();
    }

    @Override
    public List<Map<String, Object>> queryCourseListByCurrentStudent(Long sno) {
        // 查询该学号对应的所有考试成绩
        return studentMapper.findCoursesBySno(sno);
    }
}
